package xyz.chatboxapp.chatbox.ai;

import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GeminiService {
    private static final String TAG = "SystemOverlay";
    private OkHttpClient httpClient;
    
    public GeminiService() {
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }
    
    public interface Callback {
        void onSuccess(String candidatesJson);
        void onError(String errorCode, String errorMessage);
    }
    
    public void generateCandidates(String baseUrl, String model, String userText, String apiKey, Callback callback) {
        try {
            Log.i(TAG, "generateCandidates() branch = GEMINI");
            
            // Build Google Generative Language API URL (respect baseUrl path if provided)
            String glBase = (baseUrl != null && baseUrl.length() > 0) ? baseUrl : "https://generativelanguage.googleapis.com";
            if (glBase.endsWith("/")) glBase = glBase.substring(0, glBase.length() - 1);
            String apiUrl;
            try {
                String lower = glBase.toLowerCase();
                boolean hasV1beta = lower.contains("/v1beta");
                boolean hasModels = lower.contains("/v1beta/models");
                if (hasV1beta) {
                    if (hasModels) {
                        apiUrl = glBase + "/" + model + ":generateContent";
                    } else {
                        apiUrl = glBase + "/models/" + model + ":generateContent";
                    }
                } else {
                    apiUrl = glBase + "/v1beta/models/" + model + ":generateContent";
                }
            } catch (Exception _e) {
                apiUrl = glBase + "/v1beta/models/" + model + ":generateContent";
            }
            
            Log.i(TAG, "GEMINI request url=" + apiUrl);
            
            // Build Gemini request body using the passed-in text as the final prompt
            JSONObject body = new JSONObject();
            JSONArray contents = new JSONArray();
            JSONObject part = new JSONObject();
            part.put("text", userText);
            JSONArray parts = new JSONArray();
            parts.put(part);
            JSONObject content = new JSONObject();
            content.put("parts", parts);
            contents.put(content);
            body.put("contents", contents);
            
            // Debug: prompt preview
            try {
                String prev = userText.replaceAll("\\s+", " ");
                if (prev.length() > 200) prev = prev.substring(0, 200);
                Log.i(TAG, "GEMINI prompt preview len=" + userText.length() + " preview=\"" + prev + "\"");
            } catch (Exception ignored) {}
            
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            final Request req = new Request.Builder()
                    .url(apiUrl + "?key=" + apiKey)
                    .addHeader("Content-Type", "application/json")
                    .post(RequestBody.create(body.toString(), JSON))
                    .build();
            
            new Thread(() -> {
                try (Response resp = httpClient.newCall(req).execute()) {
                    Log.i(TAG, "GEMINI http status=" + resp.code());
                    
                    if (!resp.isSuccessful()) {
                        String emsg = "HTTP " + resp.code();
                        try {
                            String bodyS = resp.body() != null ? resp.body().string() : "";
                            Log.w(TAG, "GEMINI http_error bodyLen=" + (bodyS != null ? bodyS.length() : 0));
                        } catch (Exception ignored) {}
                        callback.onError("http_error", emsg);
                        return;
                    }
                    
                    String respStr = resp.body() != null ? resp.body().string() : "";
                    Log.i(TAG, "GEMINI resp len=" + (respStr != null ? respStr.length() : 0));
                    
                    JSONObject rj = new JSONObject(respStr);
                    JSONArray candidates = rj.optJSONArray("candidates");
                    if (candidates == null || candidates.length() == 0) {
                        callback.onError("no_candidates", "No candidates returned");
                        return;
                    }
                    
                    JSONArray texts = new JSONArray();
                    for (int i = 0; i < candidates.length(); i++) {
                        JSONObject cand = candidates.getJSONObject(i);
                        JSONObject contentObj = cand.optJSONObject("content");
                        if (contentObj == null) continue;
                        JSONArray partsArray = contentObj.optJSONArray("parts");
                        if (partsArray == null) continue;
                        for (int j = 0; j < partsArray.length(); j++) {
                            JSONObject partObj = partsArray.getJSONObject(j);
                            String txt = partObj.optString("text", "");
                            if (txt.length() > 0) texts.put(txt);
                        }
                    }
                    
                    JSONObject payload = new JSONObject();
                    payload.put("candidates", texts);
                    
                    // Debug: content preview
                    try {
                        String contentPreview = texts.length() > 0 ? texts.getString(0) : "";
                        String prev = contentPreview.replaceAll("\\s+", " ");
                        if (prev.length() > 200) prev = prev.substring(0, 200);
                        Log.i(TAG, "GEMINI content preview len=" + contentPreview.length() + " preview=\"" + prev + "\"");
                    } catch (Exception ignored) {}
                    
                    callback.onSuccess(payload.toString());
                } catch (Exception e) {
                    String msg = e.getMessage() == null ? "error" : e.getMessage().replace("\n", " ");
                    Log.e(TAG, "GEMINI exception: " + msg);
                    callback.onError("exception", msg);
                }
            }).start();
        } catch (Exception e) {
            String msg = e.getMessage() == null ? "error" : e.getMessage().replace("\n", " ");
            Log.e(TAG, "generateCandidates() bad_args: " + msg);
            callback.onError("bad_args", msg);
        }
    }
}